<?php


namespace app\common\business;


use app\common\lib\Snowflake;
use think\Exception;
use think\facade\Cache;

class Order extends BusBase
{

    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\Order();
    }

    public function save(array $data)
    {
        //生成订单号
        $work_id = rand(1, 1023);
        $order_id = Snowflake::getInstance()->setWorkId($work_id)->id();
        //获取sku信息
        $cartObj = new Cart();
        $sku_data = $cartObj->lists($data['user_id'], $data['sku_ids']);
        if (!$sku_data) {
            return false;
        }

        //组装order_goods数据
        $new_res = array_map(function ($v) use ($order_id) {
            $v['sku_id'] = $v['id'];
            unset($v['id']);
            $v['order_id'] = $order_id;

            return $v;
        }, $sku_data);

        //计算总价
        $total_price = array_sum(array_column($sku_data, 'total_price')); //获得订单总价
        //组装数据
        $order_data = [
            'user_id' => $data['user_id'],
            'order_id' => $order_id,
            'total_price' => $total_price,
            'address_id' => $data['address_id'],
        ];


        $this->model->startTrans();
        try {
            //订单入库 order
            $id = $this->add($order_data);
            if (!$id) {
                return 0;
            }
            //新增order_goods
            $order_goods_res = (new OrderGoods())->saveAll($new_res);
            if (!$order_goods_res) {
                throw  new \Exception('插入order_goods数据失败');
            }
            //goods_sku更新
            $sku_res = (new GoodsSku())->updateStock($sku_data);
            //goods更新
            //删除购物车里的商品
            $cartObj->del($data['user_id'], $data['sku_ids']);

            $this->model->commit();
            //把当前订单ID放入延迟队列中,定期检测订单是否已经支付(订单有效期是20分钟,超过这个时间,我们需要取消这个订单,然后库存+操作)


            try { //这里使用try的作用是,就算Redis有问题不能影响正常订单的生成,如果有问题可以记录日志来处理.
                Cache::zAdd('order_status_key', time() + 20 * 60, $order_id);
            } catch (Exception $e) {
                //记录日志,添加监控,异步根据监控内容处理
            }

            return ['id' => (string)$order_id];

        } catch (Exception $e) {
            $this->model->rollback();
            return false;
        }

    }

    public function detail(array $data)
    {
        try {
            $orders = $this->model->getByCondition($data);
        } catch (Exception $e) {
            return [];
        }

        if (!$orders) {
            return [];
        }

        $orders = !empty($orders) ? $orders[0] : [];
        if (empty($orders)) {
            return [];
        }

        $orders['id'] = intval($orders['id']);
        $orders['consignee_info'] = '上海市xxxx';
//        $orders['mall_title'] = '商城名称XXX';
//        $orders['price'] = $orders['total_price'];
        $order_goods = (new OrderGoods())->getByOrderId($data['order_id']);
        $orders['malls'] = $order_goods;

        return $orders;
    }

    //每秒检测一次有序集合的订单
    public function checkOrderStatus()
    {
        //获取key是order_status_key,并且分数是0 到 当前时间,限制条数是10条的数据.
        $res = Cache::store('redis')->zRangeByScore('order_status_key', 0, time(), ['limit' => [0, 10]]);
        if (empty($res) || empty($res[0])) {
            return false;
        }

        try {
            $del_redis = Cache::store('redis')->zRem('order_status_key', $res[0]);
        } catch (Exception $e) {
            //记录日志
            $del_redis = '';
        }


        if ($del_redis) {
            echo '订单ID:' . $res[0] . '在规定时间内没有完成支付,我们判定为无效订单删除' . PHP_EOL;
        }

        /**
         * 1.启用事物
         * 2.更新order和order_goods状态
         * 3.增加goods库存
         */
    }
}